<template>
  <div class="department-detail-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>科室详情</h2>
      <div class="header-actions">
        <el-button type="primary" :icon="Edit" @click="handleEdit">
          编辑
        </el-button>
      </div>
    </div>

    <!-- 科室基本信息卡片 -->
    <el-card class="basic-info-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
        </div>
      </template>

      <div class="info-grid">
        <div class="info-item">
          <span class="info-label">科室名称：</span>
          <span class="info-value">{{ department?.name }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">科室级别：</span>
          <span class="info-value">{{ department?.level }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">科室状态：</span>
          <el-tag :type="department?.status === '显示' ? 'success' : 'info'">{{ department?.status }}</el-tag>
        </div>
        <div class="info-item">
          <span class="info-label">所属医院：</span>
          <span class="info-value">{{ department?.hospitalName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">上级科室：</span>
          <span class="info-value">{{ department?.parentName || '无' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">医生数量：</span>
          <span class="info-value">{{ department?.doctorCount }}</span>
        </div>
      </div>

      <div class="info-item full-width">
        <span class="info-label">科室简介：</span>
        <div class="info-value">{{ department?.description }}</div>
      </div>
    </el-card>

    <!-- 医生列表卡片 -->
    <el-card class="doctors-card">
      <template #header>
        <div class="card-header">
          <span>医生团队</span>
          <div class="header-actions">
            <el-button type="primary" :icon="Plus" @click="handleAddDoctor">
              添加医生
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="doctors"
        style="width: 100%"
        v-loading="doctorsLoading"
        row-key="id"
      >
        <el-table-column prop="name" label="医生姓名" width="120" />

        <el-table-column prop="title" label="职称" width="120" />

        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.gender === '1' ? '男' : '女' }}
          </template>
        </el-table-column>

        <el-table-column prop="age" label="年龄" width="80" />

        <el-table-column prop="phone" label="联系电话" width="150" />

        <el-table-column prop="goodAt" label="擅长领域" min-width="200" />

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-space wrap>
              <el-button
                type="primary"
                size="small"
                @click="handleViewDoctor(row)"
              >
                查看详情
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="doctorsPagination.currentPage"
          v-model:page-size="doctorsPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="doctorsPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleDoctorsSizeChange"
          @current-change="handleDoctorsCurrentChange"
        />
      </div>
    </el-card>

    <!-- 下级科室卡片 -->
    <el-card class="sub-departments-card" v-if="department?.level === '一级'
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit, Plus } from '@element-plus/icons-vue'
import { departmentApi, doctorApi } from '@/api/index'
import type { DepartmentDetail, DoctorItem } from '@/api/index'

/**
 * 智慧医疗系统 - 科室详情页面
 * 功能：展示科室的详细信息，包括基本信息、医生团队等
 */

// 接口类型定义
interface DepartmentDetail {
  id: number
  name: string
  level: string
  status: string
  description?: string
  hospitalId: number
  hospitalName: string
  parentId?: number
  parentName?: string
  doctorCount: number
  uploader: string
  uploadTime: string
}

interface DoctorItem {
  id: number
  name: string
  title: string
  gender: string
  age: number
  phone: string
  goodAt: string
  departmentId: number
  departmentName: string
  hospitalId: number
}

// 响应式数据
const department = ref<DepartmentDetail | null>(null)
const doctors = ref<DoctorItem[]>([])
const loading = ref(false)
const doctorsLoading = ref(false)

// 分页信息
const doctorsPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 路由相关
const route = useRoute()
const router = useRouter()
const hospitalId = Number(route.params.hospitalId)
const departmentId = Number(route.params.id)

// 生命周期
onMounted(() => {
  loadDepartmentDetail()
  loadDoctors()
})

/**
 * 加载科室详情数据
 */
const loadDepartmentDetail = async () => {
  loading.value = true
  try {
    const response = await departmentApi.getDetail(departmentId)
    if (response.code === 200) {
      department.value = response.data
    } else {
      ElMessage.error('获取科室详情失败')
    }
  } catch (error) {
    console.error('加载科室详情出错:', error)
    ElMessage.error('加载科室详情失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 加载医生数据
 */
const loadDoctors = async () => {
  doctorsLoading.value = true
  try {
    const params = {
      departmentId,
      currentPage: doctorsPagination.currentPage,
      pageSize: doctorsPagination.pageSize
    }

    const response = await doctorApi.getListByDepartment(params)
    if (response.code === 200) {
      const data = response.data
      doctors.value = data.items
      doctorsPagination.total = data.totalCount
    } else {
      ElMessage.error('获取医生数据失败')
    }
  } catch (error) {
    console.error('加载医生数据出错:', error)
    ElMessage.error('加载医生数据失败，请重试')
  } finally {
    doctorsLoading.value = false
  }
}

/**
 * 返回上一页
 */
const handleBack = () => {
  router.back()
}

/**
 * 跳转到编辑页面
 */
const handleEdit = () => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/edit/${departmentId}`
  })
}

/**
 * 添加医生
 */
const handleAddDoctor = () => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/${departmentId}/doctor/add`
  })
}

/**
 * 查看医生详情
 */
const handleViewDoctor = (row: DoctorItem) => {
  router.push({
    path: `/content/hospital/${hospitalId}/doctor/detail/${row.id}`
  })
}

/**
 * 医生列表分页大小改变
 */
const handleDoctorsSizeChange = (size: number) => {
  doctorsPagination.pageSize = size
  loadDoctors()
}

/**
 * 医生列表当前页改变
 */
const handleDoctorsCurrentChange = (current: number) => {
  doctorsPagination.currentPage = current
  loadDoctors()
}
</script>

<style lang="scss" scoped>
.department-detail-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .basic-info-card,
  .doctors-card,
  .sub-departments-card {
    margin-bottom: 24px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    margin-bottom: 24px;
  }

  .info-item {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 8px;

    .info-label {
      font-weight: 500;
      margin-right: 8px;
      min-width: 100px;
    }

    .info-value {
      flex: 1;
    }
  }

  .full-width {
    grid-column: 1 / -1;
  }

  .pagination-container {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
  }

  .back-button-container {
    margin-top: 32px;
    text-align: center;
  }
}
</style>